package net.litxuf.Util.divpage;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

public class Pagination {

	static Logger logger = Logger.getLogger(Pagination.class);
	private int totalPage = 1;// 总页数

	private int curPage = 1;

	private int pageSize = 10;

	private List list=null;
	
	public List getList() {
		return list;
	}

	public void setList(List list){
		this.list=list;
	}
	public int getPageSize() {
		return pageSize;
	}

	public int getCurPage() {
		return curPage;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public Pagination(int totalRowCount, HttpServletRequest request) {

		try {
			// 每个页面显示的记录条数
			String pageSizes = (String) request.getParameter("pageSize");

			// 当前页
			String curPages = (String) request.getParameter("curPage");
			// 每行默认显示10条记录
			if (null == pageSizes || pageSizes.equals("")) {
				pageSize = 10;
				logger.info("使用分页方法：当前每页显示默认值" + pageSize + "条记录");
			} else {
				pageSize = Integer.parseInt(pageSizes);
				logger.info("使用分页方法：每页显示" + pageSize + "条记录");
			}

			// 总页数
			if (totalRowCount % pageSize == 0) {
				totalPage = totalRowCount / pageSize;
			} else {
				totalPage = totalRowCount / pageSize + 1;
			}
			
			
			// 当前页码的处理
			if (null == curPages || curPages.equals("")
					|| Integer.parseInt(curPages) <= 0) {
				curPage = 1;
				logger.info("使用分页方法：当前页 第" + curPage + "页");
			} else {
				// 不允许当前页码大于总页数，自动更改为最后一页
				if (Integer.parseInt(curPages) >= totalPage) {
					curPage = totalPage;
					logger.info("使用分页方法：当前页 第" + curPage + "页");
				} else {
					curPage = Integer.parseInt(curPages);
					logger.info("使用分页方法：当前页 第" + curPage + "页");
				}
			}
			
			
			request.setAttribute("pageSize", String.valueOf(pageSize));
			request.setAttribute("curPage", String.valueOf(curPage));
			request.setAttribute("totalPage", String.valueOf(totalPage));
			request.setAttribute("totalRowCount", String.valueOf(totalRowCount));

			logger.info("成功完成分页功能");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
